﻿using BasicInformation.ApiRead.Application.Command.Operation;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using Dapper;
using MediatR;
using System.Text;

namespace BasicInformation.ApiRead.Application.Handler.Operation
{
    public class GetOperationHandler : IRequestHandler<GetOperationCommand, ApiPaging<OperationModel>>
    {
        private readonly ILogger<GetOperationHandler> logger;
        private readonly DatabaseContext db;

        public GetOperationHandler(ILogger<GetOperationHandler> logger,DatabaseContext db)
        {
            this.logger = logger;
            this.db = db;
        }
        public async Task<ApiPaging<OperationModel>> Handle(GetOperationCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<OperationModel> result = new ApiPaging<OperationModel>();
            StringBuilder sql= new StringBuilder();
            StringBuilder countSql= new StringBuilder();

            sql.Append(@"SELECT
                            OperationId,
	                        OperationName,
	                        OTypeName,
	                        OperationSketch,
	                        CreatTime 
                        FROM
	                        operationmodel ");
            countSql.Append(@"SELECT
	                                COUNT(CreatTime) 
                              FROM
	                                operationmodel ");
            sql.Append(" ORDER BY OperationId  LIMIT @size OFFSET @offset");

            var parameters = new
            {
                offset = (request.index - 1) * request.size,
                size = request.size
            };
            try
            {
                var pageData = await db.DapperConnection.QueryAsync<OperationModel>(sql.ToString(), parameters);
                var totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(sql.ToString(), parameters);

                int totalPage = (int)Math.Ceiling(totalCount / (double)request.size);

                result.Msg = "操作查询成功";
                result.Code = ApiEnum.OK;
                result.Data = pageData.ToList();
                result.TotalCount = totalCount;
                result.TotalPCount = totalPage;
            }
            catch (FormatException ex)
            {
                // 添加更详细的错误日志
                logger.LogError($"数据格式转换错误: {ex.Message}, SQL: {sql}");
            }
            return await Task.FromResult(result);
        }
    }
}
